<?php
namespace app\controller\open;

use app\exception\ErrnoPlus;
use app\service\OpenAppService;
use share\service\cache\CommonCacheKeyService;
use share\controller\ApiBaseController;
use share\exception\ApiException;
use share\service\ContextService;
use share\service\RedisService;
use share\utils\Helper;
use share\controller\CommonDataSignTrait;
use share\controller\OpenAppSignTrait;

class BaseOpenController extends ApiBaseController{

    protected $appIdKey = 'appid';
    protected $signKey = 'sign';
    protected $signConfigKey = 'CommonDataSign';
    protected $signTimeKey = 't';

    protected $openApp = [];

    use CommonDataSignTrait;

    use OpenAppSignTrait;

    protected $beforeActionList = [
        // "checkOpenAppSign",
        "checkUser",
    ];

    CONST LOGIN_TOKEN_TIMEOUT = 3600;
    
    public static function authToken($userInfo){        
        $token = Helper::getUnique();
        $key = self::getAuthCacheKey($token);        
        RedisService::instance(RedisService::CACHE_DB_BASE)->setJson($key,$userInfo,self::LOGIN_TOKEN_TIMEOUT);
        return $token;
    }

    public static function getAuthInfoByToken($token){
        $key = self::getAuthCacheKey($token);
        return RedisService::instance(RedisService::CACHE_DB_BASE)->getJson($key);
    }

    public static function getAuthCacheKey($token){        
        return CommonCacheKeyService::getCacheKey(CommonCacheKeyService::CACHE_KEY_AUTH_ACCOUNT_OPEN ,['token' =>md5($token)]);
    }

    /**
     * 检查已登录用户
     */
    public function checkUser(){
      
        $token = $this->request->header('token');      
        if(empty($token)){            
            throw new ApiException("当前用户未登录",ErrnoPlus::WEB_LOGOUT);
        }
        $userInfo = self::getAuthInfoByToken($token);
        if(empty($userInfo)){
            throw new ApiException("当前用户登录信息已过期,请重新登录",ErrnoPlus::WEB_LOGOUT);
        }
        $cacheKey = self::getAuthCacheKey($token);        
        ContextService::setUserInfo($userInfo);
        return RedisService::instance(RedisService::CACHE_DB_BASE)->expire($cacheKey,self::LOGIN_TOKEN_TIMEOUT);
    }

    public function getOpenSignSecret($appId){
        $openApp = OpenAppService::fastGetByAppId($appId);
        if(empty($openApp) || $openApp['state'] != OpenAppService::STATE_OF_OK){
            throw new ApiException("应用不存在或者状态不正确",ErrnoPlus::OPEN_APP_NOT_FOUND);
        }
        $this->openApp = $openApp;
        return $openApp['app_secret'];
    }


}